#!/usr/bin/env python3
"""
S31-BSIM Installation Verification Script
Checks if all dependencies and system tools are properly installed
"""

import sys
import subprocess

def check_python_version():
    """Check Python version"""
    print("Checking Python version...")
    version = sys.version_info
    if version.major >= 3 and version.minor >= 8:
        print(f"  [OK] Python {version.major}.{version.minor}.{version.micro}")
        return True
    else:
        print(f"  [FAIL] Python {version.major}.{version.minor}.{version.micro} (requires 3.8+)")
        return False

def check_python_package(package_name, import_name=None):
    """Check if a Python package is installed"""
    if import_name is None:
        import_name = package_name
    
    try:
        __import__(import_name)
        print(f"  [OK] {package_name}")
        return True
    except ImportError:
        print(f"  [FAIL] {package_name} not found")
        return False

def check_system_command(command, name=None):
    """Check if a system command is available"""
    if name is None:
        name = command
    
    try:
        result = subprocess.run(
            [command, '--version'],
            capture_output=True,
            text=True,
            timeout=5
        )
        if result.returncode == 0:
            version_line = result.stdout.split('\n')[0]
            print(f"  [OK] {name}: {version_line}")
            return True
        else:
            print(f"  [FAIL] {name} not found or error")
            return False
    except FileNotFoundError:
        print(f"  [FAIL] {name} not found in PATH")
        return False
    except subprocess.TimeoutExpired:
        print(f"  [FAIL] {name} timeout")
        return False
    except Exception as e:
        print(f"  [FAIL] {name}: {e}")
        return False

def main():
    """Main verification routine"""
    print("="*70)
    print("  S31-BSIM Installation Verification")
    print("="*70)
    
    results = {}
    
    # Check Python version
    print("\n[1] Python Version")
    results['python_version'] = check_python_version()
    
    # Check core Python packages
    print("\n[2] Core Python Packages")
    packages = [
        ('numpy', 'numpy'),
        ('scipy', 'scipy'),
        ('matplotlib', 'matplotlib'),
        ('scikit-learn', 'sklearn'),
        ('psutil', 'psutil'),
    ]
    
    package_results = []
    for pkg_name, import_name in packages:
        package_results.append(check_python_package(pkg_name, import_name))
    results['core_packages'] = all(package_results)
    
    # Check data processing packages
    print("\n[3] Data Processing Packages")
    data_packages = [
        ('h5py', 'h5py'),
        ('requests', 'requests'),
        ('tqdm', 'tqdm'),
    ]
    
    data_results = []
    for pkg_name, import_name in data_packages:
        data_results.append(check_python_package(pkg_name, import_name))
    results['data_packages'] = all(data_results)
    
    # Check optional packages
    print("\n[4] Optional Packages")
    optional_packages = [
        ('PyWavelets', 'pywt'),
    ]
    
    optional_results = []
    for pkg_name, import_name in optional_packages:
        optional_results.append(check_python_package(pkg_name, import_name))
    results['optional_packages'] = all(optional_results)
    
    # Check system tools
    print("\n[5] System Tools (for firmware emulation)")
    tools = [
        ('qemu-system-arm', 'QEMU ARM'),
        ('arm-none-eabi-gcc', 'GCC ARM Toolchain'),
        ('make', 'GNU Make'),
    ]
    
    tool_results = []
    for cmd, name in tools:
        tool_results.append(check_system_command(cmd, name))
    results['system_tools'] = all(tool_results)
    
    # Check project files
    print("\n[6] Project Files")
    required_files = [
        'analyze_firmware_traces.py',
        'collect_firmware_traces.py',
        'preprocess_traces.py',
        'download_real_traces.py',
        'requirements.txt',
        'side_channel_attacks/attack_manager.py',
    ]
    
    import os
    file_results = []
    for filepath in required_files:
        exists = os.path.exists(filepath)
        status = "[OK]" if exists else "[FAIL]"
        print(f"  {status} {filepath}")
        file_results.append(exists)
    results['project_files'] = all(file_results)
    
    # Summary
    print("\n" + "="*70)
    print("  Verification Summary")
    print("="*70)
    
    total_checks = len(results)
    passed_checks = sum(1 for v in results.values() if v)
    
    print(f"\nPassed: {passed_checks}/{total_checks}")
    print()
    
    for category, status in results.items():
        status_str = "[OK]" if status else "[FAIL]"
        category_name = category.replace('_', ' ').title()
        print(f"  {status_str} {category_name}")
    
    print()
    
    if all(results.values()):
        print("[SUCCESS] All checks passed! S31-BSIM is ready to use.")
        print("\nNext steps:")
        print("  1. Generate datasets: python download_real_traces.py --dataset all_synthetic")
        print("  2. Run quick test: ./test_real_traces.sh")
        print("  3. View examples: ls scheme/*.json")
        return 0
    else:
        print("[WARNING] Some checks failed. Please fix the issues above.")
        print("\nCommon solutions:")
        
        if not results['core_packages'] or not results['data_packages']:
            print("  - Install Python dependencies: pip install -r requirements.txt")
        
        if not results['system_tools']:
            print("  - Install system tools:")
            print("    Ubuntu: sudo apt-get install qemu-system-arm gcc-arm-none-eabi")
            print("    macOS:  brew install qemu gcc-arm-embedded")
        
        if not results['optional_packages']:
            print("  - Optional packages missing (not critical)")
            print("    Install with: pip install PyWavelets")
        
        print("\nFor detailed help, see INSTALL.md")
        return 1

if __name__ == "__main__":
    sys.exit(main())

